<template>
  <div class="event-list">
    <h1 class="page-title">活动管理</h1>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索活动标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 150px">
            <el-option label="待开始" value="upcoming" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="table-card">
      <el-table
        :data="eventList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="活动信息" min-width="300">
          <template #default="{ row }">
            <div class="event-info">
              <el-image 
                :src="row.coverImage || '/default-event.png'" 
                fit="cover"
                class="cover-image"
              />
              <div class="event-detail">
                <div class="title">{{ row.title }}</div>
                <div class="description">{{ row.description || '暂无描述' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="时间" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <div>开始: {{ formatDateTime(row.startTime) }}</div>
              <div class="text-muted">结束: {{ formatDateTime(row.endTime) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="人数" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="getPercentage(row.currentParticipants, row.maxParticipants)" 
              :color="getProgressColor(row.currentParticipants, row.maxParticipants)"
            />
            <div class="text-center text-muted">
              {{ row.currentParticipants || 0 }} / {{ row.maxParticipants || 0 }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewDetail(row.id)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'upcoming'" 
              link 
              type="danger" 
              size="small" 
              @click="cancelEvent(row.id)"
            >
              取消
            </el-button>
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="deleteEvent(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.page_size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadEvents"
        @current-change="loadEvents"
        class="pagination"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { eventApi } from '@/api/event'
import dayjs from 'dayjs'

const router = useRouter()

const loading = ref(false)
const eventList = ref([])
const dateRange = ref([])

const searchForm = reactive({
  keyword: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  page_size: 20,
  total: 0
})

onMounted(() => {
  loadEvents()
})

const loadEvents = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.page,
      page_size: pagination.page_size,
      ...searchForm
    }

    // 添加日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD')
      params.endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD')
    }

    const data = await eventApi.getEventList(params)
    
    eventList.value = data.items || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadEvents()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  dateRange.value = []
  handleSearch()
}

const viewDetail = (id) => {
  router.push(`/events/${id}`)
}

const cancelEvent = (id) => {
  ElMessageBox.prompt('请输入取消原因', '取消活动', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入取消原因',
    inputValidator: (value) => {
      if (!value) {
        return '请输入取消原因'
      }
      return true
    }
  }).then(async ({ value }) => {
    try {
      await eventApi.cancelEvent(id, value)
      ElMessage.success('活动已取消')
      loadEvents()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }).catch(() => {})
}

const deleteEvent = (id) => {
  ElMessageBox.confirm('确定要删除该活动吗？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      await eventApi.deleteEvent(id)
      ElMessage.success('删除成功')
      loadEvents()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

const getPercentage = (current, max) => {
  if (!max || max === 0) return 0
  return Math.round((current / max) * 100)
}

const getProgressColor = (current, max) => {
  const percentage = getPercentage(current, max)
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
}

const getStatusType = (status) => {
  const types = {
    upcoming: 'primary',
    ongoing: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    upcoming: '待开始',
    ongoing: '进行中',
    completed: '已结束',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const formatDateTime = (date) => {
  return date ? dayjs(date).format('MM-DD HH:mm') : '-'
}
</script>

<style scoped>
.event-list {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.event-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.cover-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  flex-shrink: 0;
}

.event-detail {
  flex: 1;
  min-width: 0;
}

.title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.description {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-info {
  font-size: 13px;
  line-height: 1.6;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.text-center {
  text-align: center;
  margin-top: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

